package com.jeady.jxcompose

import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.Slider
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import com.jeady.jxcompose.Utils.showToast

private val TAG = "[Slider]"
@Composable
fun SliderInput(modifier: Modifier = Modifier,
                range: ClosedFloatingPointRange<Float> = 0f..10f,
                onValueChanged: (Float)->Unit
){
    val context = LocalContext.current
    var timeSlider by remember { mutableFloatStateOf(range.start) }
    Row(modifier, verticalAlignment = Alignment.CenterVertically){
        var valueInput by remember{ mutableStateOf(timeSlider.toInt().toString()) }
        Slider(
            timeSlider,{newV: Float->
                timeSlider = newV
                valueInput = newV.toInt().toString()
                onValueChanged(timeSlider)
            },
            modifier = Modifier
                .weight(1f)
                .padding(end = 10.dp),
            valueRange = range, steps = (range.endInclusive-range.start).toInt()+1
        )
        BasicTextField(valueInput, onValueChange = fun(newValue: String){
                if(newValue.length>5){
                    showToast(context, "超出长度")
                    return
                }
                if(newValue.matches(Regex("[\\d.]*"))){
                    valueInput = newValue
                }
                if(valueInput.isNotBlank()){
                    onValueChanged(valueInput.toFloat())
                }
            }, Modifier.width(50.dp),
            singleLine = true,
            textStyle = TextStyle(textAlign = TextAlign.Center),
            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)
        )
    }
}